<template>
  <view style="display: flex; flex-direction: column; margin-top: 10rpx">
    <view style="display: flex; justify-content: space-between">
      <div style="opacity: 0">
        <van-icon name="passed" size="2em" style="margin-left: 30rpx" />
      </div>
      <div>
        <span style="font-weight: bold; font-size: 40rpx; margin-right: 10rpx">
          {{
            date.getDate() < 10 ? "0" + date.getDate() : date.getDate()
          }}</span
        ><span style="font-size: 25rpx; margin-right: 30rpx"
          >{{ date.getFullYear() }}年{{ date.getMonth() + 1 }}月</span
        >
        <span></span><van-icon name="arrow-down" @click="onDisplay" />
      </div>
      <!-- 打勾按钮 -->
      <div>
        <van-icon
          name="passed"
          size="2em"
          style="margin-right: 20rpx"
          @click="submit"
        />
      </div>
    </view>
    <van-divider hairline customStyle="margin:20rpx;border-color:#ebedf0;" />
    <van-toast id="van-toast" />
    <!-- 日历下拉选择日记的时间 -->
    <van-calendar
      :default-date="date.getTime()"
      color="#66ccff"
      :min-date="minDate"
      :max-date="maxDate"
      :show-mark="false"
      :show-subtitle="false"
      :show-title="false"
      poppable
      position="top"
      :show="show"
      @close="onClose"
      @confirm="onConfirm"
    />
    <!-- 图片上传 -->
    <view style="margin-left: 20rpx"
      ><van-uploader
        :file-list="fileList"
        :deletable="true"
        @delete="deleteImage"
        @after-read="afterRead"
    /></view>
    <van-divider hairline customStyle="margin:20rpx;border-color:#ebedf0;" />
    <van-field
      :value="title"
      placeholder="给这篇日记起个标题吧"
      placeholder-style="font-size:large;font-weight:normal"
      size="large"
      input-align="center"
      border="false"
      @input="change"
    />
    <!-- 富文本编辑器 -->
    <view class="container">
      <view class="page-body">
        <view class="wrapper">
          <view
            class="toolbar"
            @tap="format"
            style="margin-top: 20rpx; height: 250rpx; overflow-y: auto"
          >
            <view
              :class="formats.bold ? 'ql-active' : ''"
              class="iconfont icon-zitijiacu"
              data-name="bold"
            ></view>
            <view
              :class="formats.italic ? 'ql-active' : ''"
              class="iconfont icon-zitixieti"
              data-name="italic"
            ></view>
            <view
              :class="formats.underline ? 'ql-active' : ''"
              class="iconfont icon-zitixiahuaxian"
              data-name="underline"
            ></view>
            <view
              :class="formats.strike ? 'ql-active' : ''"
              class="iconfont icon-zitishanchuxian"
              data-name="strike"
            ></view>
            <view
              :class="formats.align === 'left' ? 'ql-active' : ''"
              class="iconfont icon-zuoduiqi"
              data-name="align"
              data-value="left"
            ></view>
            <view
              :class="formats.align === 'center' ? 'ql-active' : ''"
              class="iconfont icon-juzhongduiqi"
              data-name="align"
              data-value="center"
            ></view>
            <view
              :class="formats.align === 'right' ? 'ql-active' : ''"
              class="iconfont icon-youduiqi"
              data-name="align"
              data-value="right"
            ></view>
            <view
              :class="formats.align === 'justify' ? 'ql-active' : ''"
              class="iconfont icon-zuoyouduiqi"
              data-name="align"
              data-value="justify"
            ></view>
            <view
              :class="formats.fontSize === '24px' ? 'ql-active' : ''"
              class="iconfont icon-fontsize"
              data-name="fontSize"
              data-value="24px"
            ></view>
            <view
              :class="formats.color === '#0000ff' ? 'ql-active' : ''"
              class="iconfont icon-text_color"
              data-name="color"
              data-value="#0000ff"
            ></view>
            <view
              :class="formats.backgroundColor === '#00ff00' ? 'ql-active' : ''"
              class="iconfont icon-fontbgcolor"
              data-name="backgroundColor"
              data-value="#00ff00"
            ></view>

            <view class="iconfont icon-date" @tap="insertDate"></view>
            <view
              class="iconfont icon--checklist"
              data-name="list"
              data-value="check"
            ></view>
            <view
              :class="formats.list === 'ordered' ? 'ql-active' : ''"
              class="iconfont icon-youxupailie"
              data-name="list"
              data-value="ordered"
            ></view>
            <view
              :class="formats.list === 'bullet' ? 'ql-active' : ''"
              class="iconfont icon-wuxupailie"
              data-name="list"
              data-value="bullet"
            ></view>
            <view class="iconfont icon-undo" @tap="undo"></view>
            <view class="iconfont icon-redo" @tap="redo"></view>
            <view class="iconfont icon-fengexian" @tap="insertDivider"></view>
            <view
              :class="formats.header === 1 ? 'ql-active' : ''"
              class="iconfont icon-format-header-1"
              data-name="header"
              :data-value="1"
            ></view>
            <view
              :class="formats.script === 'sub' ? 'ql-active' : ''"
              class="iconfont icon-zitixiabiao"
              data-name="script"
              data-value="sub"
            ></view>
            <view
              :class="formats.script === 'super' ? 'ql-active' : ''"
              class="iconfont icon-zitishangbiao"
              data-name="script"
              data-value="super"
            ></view>
            <view class="iconfont icon-shanchu" @tap="clear"></view>
          </view>
          <view class="editor-wrapper">
            <editor
              id="editor"
              class="ql-container"
              :placeholder="placeholder"
              @input="getEditorValue"
              showImgSize
              showImgToolbar
              showImgResize
              @statuschange="onStatusChange"
              :read-only="readOnly"
              @ready="onEditorReady"
            >
            </editor>
          </view>
        </view>
      </view>
    </view>
    <view style="display: flex; justify-content: space-between; margin: 30rpx">
      <van-tag round color="#ebedf0" text-color="#000000" size="large">
        共&nbsp{{ wordCount }}&nbsp字</van-tag
      >
    </view>
  </view>
</template>

<script>
import Toast from "../../wxcomponents/vant/toast/toast";

const initialMinDate = (() => {
  const now = new Date(new Date().getTime());
  return new Date(
    now.getFullYear(),
    now.getMonth() - 6,
    now.getDate()
  ).getTime();
})();
const initialMaxDate = (() => {
  const now = new Date(new Date().getTime());
  return new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
})();

const fileUploadToken = "4afcf074-0825-4ffc-96b9-d3a1acd07a03"; // 替换成你的客户端上传 token，可在后台「设置」页面获取
// 得到当前的日期
const getNowDate = (() => {
  const now = new Date(new Date().getTime());
  return new Date(now.getFullYear(), now.getMonth(), now.getDate());
})();
export default {
  data() {
    return {
      date: getNowDate,
      show: false,
      minDate: initialMinDate,
      maxDate: initialMaxDate,
      fileList: [],
      returnURL: [],
      placeholder:
        "写给可爱的小同学：\n你可以在这里记录今日的生活，告诉我今天过得怎么样哟~\
      \n你可以使用图片/文字的形式，我们也提供了很多工具供你使用",
      content: "",
      wordCount: 0,
      title: "",
    };
  },
  methods: {
    onDisplay() {
      this.show = true;
    },
    onClose() {
      this.show = false;
    },
    // formatDate(date) {
    //   date = new Date(date);
    //   return `${date.getMonth() + 1}/${date.getDate()}`;
    // },
    onConfirm(event) {
      this.show = false;
      // this.date = this.formatDate(event.detail);
      this.date = event.detail;
      this.fileList = [];
      this.content = "";
      this.title = "";
      this.wordCount = 0;
      this.returnURL = [];
      this.editorCtx.setContents({
        //赋值
        html: "",
      });
      this.sjhrequest
        .run("findDiary", {
          d_date: new Date(
            this.date.getFullYear(),
            this.date.getMonth(),
            this.date.getDate()
          ).getTime(),
        })
        .then((res) => {
          // 如果已经有日记，则填入
          if (res.result.length != 0) {
            const d_content = res.result[0].d_content;
            this.title = res.result[0].d_title;
            uni
              .createSelectorQuery()
              .select("#editor")
              .context((res) => {
                this.editorCtx = res.context;
                this.editorCtx.setContents({
                  //赋值
                  html: d_content,
                });
                this.wordCount = this.trimHtml(d_content).length;
              })
              .exec();
          }
          // 处理结果
        })
        .catch((err) => {
          // 处理异常
          console.error(err);
        });
      this.sjhrequest
        .run("findDiaryImg", {
          d_date: new Date(
            this.date.getFullYear(),
            this.date.getMonth(),
            this.date.getDate()
          ).getTime(),
        })
        .then((res) => {
          // 如果已经有图片，则填入
          if (typeof res.result != "undefined" && res.result.length != 0) {
            for (let i in res.result) {
              this.fileList.push({
                path: res.result[i].img_url,
                size: res.result[i].size,
                url: res.result[i].img_url,
              });
            }
          }
          // 处理结果
        })
        .catch((err) => {
          // 处理异常
          console.error(err);
        });
    },
    afterRead(event) {
      const { file } = event.detail;
      this.fileList.push({ ...file, url: file.url });
    },
    beforeRead(event) {},
    deleteImage(event) {
      // 在库里，则从库里删除
      if (typeof this.fileList[event.detail.index].url != "undefined") {
        this.sjhrequest
          .run("deleteDiaryImg", {
            d_date: new Date(
              this.date.getFullYear(),
              this.date.getMonth(),
              this.date.getDate()
            ).getTime(),
            img_url: this.fileList[event.detail.index].url,
          })
          .then((res) => {
            Toast.success("删除成功");
          })
          .catch((err) => {
            Toast.fail("删除失败");
          });
      }
      // 删除fileList中对应的图片
      this.fileList.splice(event.detail.index, 1);
    },
    // 输入框修改，标题
    change(e) {
      this.title = e.detail;
    },
    // 富文本编辑器
    readOnlyChange() {
      this.readOnly = !this.readOnly;
    },
    onEditorReady() {
      uni
        .createSelectorQuery()
        .select("#editor")
        .context((res) => {
          this.editorCtx = res.context;
        })
        .exec();
    },
    undo() {
      this.editorCtx.undo();
    },
    redo() {
      this.editorCtx.redo();
    },
    getEditorValue(e) {
      this.content = e.detail.html;
      this.wordCount = e.detail.text.length - 1;
    },
    format(e) {
      let { name, value } = e.target.dataset;
      if (!name) return;
      this.editorCtx.format(name, value);
    },
    onStatusChange(e) {
      const formats = e.detail;
      this.formats = formats;
    },
    insertDivider() {
      this.editorCtx.insertDivider({
        success: function () {},
      });
    },
    clear() {
      this.editorCtx.clear({
        success: function (res) {},
      });
    },
    removeFormat() {
      this.editorCtx.removeFormat();
    },
    insertDate() {
      const formatDate = `${this.date.getFullYear()}/${
        this.date.getMonth() + 1
      }/${this.date.getDate()}`;
      this.editorCtx.insertText({
        text: formatDate,
      });
    },
    // 存到到数据库
    async submit() {
      if(this.title == ""){
        Toast("标题不能为空哟")
        return;
      }
      Toast.loading({
        message: "加载中...",
        forbidClick: true,
      });
      // 构建要上传的文件对象
      for (let index in this.fileList) {
        // 只有没传过才传
        if (typeof this.fileList[index].url == "undefined") {
          const file = {
            path: this.fileList[index].path,
          };
          // 通过 inspirecloud.file.upload 实现上传
          await this.sjhrequest.file
            .upload(file.path.split("/").pop(), file, {
              token: fileUploadToken,
            })
            .then((data) => {
              // 上传成功
              this.returnURL.push(data.url); // 保存下来url
            })
            .catch((error) => {
              Toast.fail("上传失败");
            });
        }
      }
      this.sjhrequest
        .run("insertDiary", {
          d_date: new Date(
            this.date.getFullYear(),
            this.date.getMonth(),
            this.date.getDate()
          ).getTime(),
          d_title: this.title,
          d_content: this.content,
          d_location: "",
        })
        .then((res) => {
          Toast.success("上传成功");
        })
        .catch((err) => {
          // 处理异常
          Toast.fail("上传失败");
        });

      for (let index in this.returnURL) {
        // 只有未上传过的才传
        this.sjhrequest
          .run("insertDiaryImg", {
            img_url: this.returnURL[index],
            d_date: new Date(
              this.date.getFullYear(),
              this.date.getMonth(),
              this.date.getDate()
            ).getTime(),
          })
          .then((res) => {
            Toast.success("上传成功");
          })
          .catch((err) => {
            Toast.fail("上传失败");
          });
      }
    },
    // 获取html中文字的个数
    trimHtml(str) {
      str = str.replace(/(\n)/g, "");
      str = str.replace(/(\t)/g, "");
      str = str.replace(/(\r)/g, "");
      str = str.replace(/<\/?[^>]*>/g, "");
      str = str.replace(/\s*/g, "");
      str = str.replace(/<[^>]*>/g, "");
      return str;
    },
  },
  onLoad(option) {
    if (typeof option.obj != "undefined") {
      this.date = new Date(JSON.parse(decodeURIComponent(option.obj)));
    }
    this.sjhrequest
      .run("findDiary", {
        d_date: this.date.getTime(),
      })
      .then((res) => {
        // 如果已经有日记，则填入
        if (res.result.length != 0) {
          const d_content = res.result[0].d_content;
          this.title = res.result[0].d_title;
          uni
            .createSelectorQuery()
            .select("#editor")
            .context((res) => {
              this.editorCtx = res.context;
              this.editorCtx.setContents({
                //赋值
                html: d_content,
              });
              this.wordCount = this.trimHtml(d_content).length;
            })
            .exec();
        }
        // 处理结果
      })
      .catch((err) => {
        // 处理异常
        console.error(err);
      });
    this.sjhrequest
      .run("findDiaryImg", {
        d_date: this.date.getTime(),
      })
      .then((res) => {
        // 如果已经有图片，则填入
        if (typeof res.result != "undefined" && res.result.length != 0) {
          for (let i in res.result) {
            this.fileList.push({
              path: res.result[i].img_url,
              size: res.result[i].size,
              url: res.result[i].img_url,
            });
          }
        }
        // 处理结果
      })
      .catch((err) => {
        // 处理异常
        console.error(err);
      });
  },
  created() {},
};
</script>
<style>
@import "./css/editor-icon.css";
page {
  background-color: white;
}

.page-body {
  height: calc(100vh - var(--window-top) - var(--status-bar-height));
}

.wrapper {
  height: 100%;
}

.editor-wrapper {
  height: calc(100vh - var(--window-top) - var(--status-bar-height) - 140px);
  background: #fff;
}

.iconfont {
  display: inline-block;
  padding: 8px 8px;
  width: 24px;
  height: 24px;
  cursor: pointer;
  font-size: 20px;
}

.toolbar {
  box-sizing: border-box;
  border-bottom: 0;
  font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
}

.ql-container {
  box-sizing: border-box;
  padding: 12px 15px;
  width: 100%;
  min-height: 30vh;
  height: 100%;
  margin-top: 20px;
  font-size: 16px;
  line-height: 1.5;
}

.ql-active {
  color: #06c;
}

.ql-editor.ql-blank:before {
  /* 此处设置 placeholder 样式 */
  color: rgba(0, 0, 0, 0.5);
  font-style: normal;
}
</style>
